package person.bing.fbcloud.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import person.bing.fbcloud.common.core.constant.CommonConstant;
import person.bing.fbcloud.common.core.exception.CheckedException;

/**
 * 验证码校验
 * @author: mengfanbing
 * @date: 2020/9/14 17:21
 */
@Component
@AllArgsConstructor
public class CaptchaFilter extends AbstractGatewayFilterFactory {
    private RedisTemplate redisTemplate;
    @Override
    public GatewayFilter apply(Object config) {
        return ((exchange, chain) -> {
            MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
            String grantType = queryParams.getFirst("grant_type");
            if (grantType == null){
                return chain.filter(exchange);
            }
            if (grantType.equals("client_credentials")){
                return chain.filter(exchange);
            }
            String code = exchange.getRequest().getQueryParams().getFirst(CommonConstant.CODE);
            String randomStr = exchange.getRequest().getQueryParams().getFirst(CommonConstant.RANDOM_STR);
            Object codeFromRedis = redisTemplate.opsForValue().get(CommonConstant.DEFAULT_CODE + randomStr);
            if (StrUtil.isEmpty(code)){
                throw new CheckedException("验证码不能为空");
            }
            if (ObjectUtil.isNull(codeFromRedis)){
                throw new CheckedException("验证码过期");
            }
            if (!code.toString().equals(codeFromRedis)){
                throw new CheckedException("验证码错误");
            }
            return chain.filter(exchange);
        });
    }
}
